%%
% code mo ta thi nghiem 01.
% vecto dac trung cua anh input duoc so sanh voi tung vector dac trung
% trong csdl. O day chung ta su dung lai CSDL cua tac gia paper: 'Tied Factor Analysis for Face Recognition
%across Large Pose Differences'
%Simon J.D. Prince, Member, IEEE, James H. Elder, Member, IEEE,
%Jonathan Warrell, Member, IEEE, and Fatima M. Felisberti
% CSDL ta chi dung 2 tap: fa va ql (0 va -22.5)
%
function MAP = FaceRetrieval_ThuNghiem01
    %% doc file fa va ql tuong ung
    
    % sinh nghia cac mang luu gia tri tuong ung.
    dieuKien = {'fa','ql'};
    
    allpixelData=[];
    for(dk = 1:length(dieuKien))
        fileName = sprintf('./PixelDataTri_%s.mat',dieuKien{dk});
        load(fileName);
        allpixelData=[allpixelData pixelData];
        
    end
    %% tinh so cot
    soCot = size(allpixelData,2);
    
    %% tim ra duoc danh sach cac x trong CSDL
    for(cot=1:soCot)
        X{cot} = allpixelData(:,cot);
    end
    
    %% tim khoan cac eulid cua 1 xi voi tat ca cac xi+1->x319*2
    for(irun = 1: length(X))
        fprintf('\ndang su dung X thu %d \n',irun);
        % tim duoc x input
        Xp = X{irun};
        
        % dinh nghia mang se giu gia tri khi tinh khoan cach eulid
        X_Eulid = [];
        for(jrun=1: length(X))
            if(isequal(irun,jrun)==0)
                % tim x thu k trong CSDL voi dk Xk phai khac Xp
                Xk = X{jrun};
                temp = 0;
                for(i=1: size(allpixelData,1))
                     temp = temp+((Xp(i)-Xk(i))^2);
                end
                X_Eulid=[X_Eulid; sqrt(temp)];
            else
                % truong hop irun  = jrun thi ta cho gia tri la be nhat
                X_Eulid=[X_Eulid; -10000];
            end
        end
        % insert X_Eulid vao mang E
        E{irun} = X_Eulid;
    end
    
    %% tinh khoan cach AP giua cac tap.
    % tim gia tri cua x thu i (vd: voi x1 thi gia tri thu i cua x1 la x320)
    for(i = 1: length(X)) % n=638
        fprintf('dang chay toi i=%d\n',i);
        if(i<=(length(X)/2))
            giaTriThuI{i} = E{i}((length(X)/2)+i);
        else
            giaTriThuI{i} = E{i}(i-(length(X)/2));
        end
    end
    
    % ta sap xep cac cap gia tri giam dan
    for(i = 1: length(X)) % n=638
        % sap xep E 
        temp = sort(E{i});
        
        % loai bo phan tu tren cung
        E_sort{i} = temp(2:length(temp),:);
    end
    
    % tinh gia tri AP tai moi X.
    for(i = 1: length(X)) % n=638
        vitri = find(E_sort{i}==giaTriThuI{i});
        AP{i} = 1/vitri;
    end
    
    % tinh trung binh cac AP
    MAP = 0;
    for(i = 1: length(AP)) % n=638
         MAP = MAP + AP{i};
    end
    MAP = MAP/length(AP);
   s = 0;
end